/**
 * 定义命名空间 
 */
Ext.ns("divo.admin.test")
Ext.ns("divo.admin.portal")
Ext.ns("divo.admin.user")
Ext.ns("divo.admin.group")
Ext.ns("divo.admin.menu")

Ext.ns("divo.xf.producer")
Ext.ns("divo.xf.projecter")
Ext.ns("divo.xf.checker")
Ext.ns("divo.xf.product")
Ext.ns("divo.xf.newproduct")
Ext.ns("divo.xf.queryproduct")
Ext.ns("divo.xf.checkreport")
Ext.ns("divo.xf.corpuser")
Ext.ns("divo.xf.mainter")
Ext.ns("divo.xf.advisor")
Ext.ns("divo.xf.auditproduct")
Ext.ns("divo.xf.querycheckreport")
//EOP
;/**
 * 用户组管理
 */
divo.admin.group.MainPanel = Ext.extend(Ext.Panel, {
	initComponent : function() {
		this.portletDefinitions = [{
			id : 'functional',
			text : '菜单项权限',
			xtype : "panel.admin.GroupFunctionalPermissionsGridPanel",
			config : {
			    menuItemId : this.menuItemId
			}
		}, {
			id : 'global',
			text : '全局权限',
			xtype : "panel.admin.GroupGlobalPermissionsGridPanel",
			config : {
			    menuItemId : this.menuItemId
			}
		}]
	
		this.groupGridPanelId = this.myId("group")
		this.portalId = this.myId('portal')
		this.portalMgr = new Ext.ux.PortalManager(
			this.portalId,
			'admin-group-portal',
			this.portletDefinitions)
		
		Ext.apply(this, {
			layout : 'tdgi_border',
			defaults : {
				border : false
			},
			border : false,
			items : [{
				stateful : true,
				stateId : this.myId('group'),
				region : 'west',
				title : '用户组一览',
				collapsible : false,
				ctCls : "j-toolbar-dark",
				width : 350,
				collapsedTitle : true,
				split : true,
				layout : 'fit',
				items : [{
					id : this.groupGridPanelId,
					xtype : "panel.admin.GroupGridPanel",
					menuItemId : this.menuItemId
				}]
			}, {  
				region : 'center',
				layout : 'fit',
                tbar : this.portalMgr.getTbar(),
                autoScroll:true,
				ctCls : "j-toolbar-dark",
				items : [{
					xtype : 'statefulportal',
					id : this.portalId,
					items : [{
						columnWidth : .25,
						style : 'padding:10px 0 10px 10px'
					}, {
						columnWidth : .25,
						style : 'padding:10px 0 10px 10px'
					}, {
						columnWidth : .25,
						style : 'padding:10px 0 10px 10px'
					}, {
						columnWidth : .25,
						style : 'padding:10px 0 10px 10px'
					}]
				}]
			}]	
		})

		this.subscribe("divo.rowSelect"+this.groupGridPanelId,this.onGroupChange,this)
		this.on('beforedestroy',function() {
		      this.unsubscribe()
		},this)

		divo.admin.group.MainPanel.superclass.initComponent.call(this)
	},
	onGroupChange : function(subj, msg, data) {
		this.portalMgr.onRefresh(msg)
	},
	initPortal : function() {
		this.portalMgr.init()

		Ext.ComponentMgr.get(this.portalId).on("drop", function() {
			this.portalMgr.saveState()
		},this)
	}
	
})

divo.admin.group.Main = function() {
	/* ----------------------- private变量 ----------------------- */
	var mp

	/* ----------------------- private方法 ----------------------- */
	// 创建布局
	function createLayout(parentPanel,menuItemId) {
		mp = new divo.admin.group.MainPanel({
			id : 'admin-group',
			menuItemId : menuItemId
		})
		parentPanel.add(mp)
		parentPanel.doLayout()
	}

	/* ----------------------- public方法 ----------------------- */
	return {

		// 初始化
		init : function(parentPanel, menuItemId) {
			createLayout(parentPanel,menuItemId)
			mp.initPortal()
		}

	} // return

}()
// EOP

;/**
 * 定义命名空间 
 */
Ext.ns("divo.panel")

Ext.ns("form.test")
Ext.ns("panel.test")
Ext.ns("window.test")
Ext.ns("grid.test")
Ext.ns("tree.test")
Ext.ns("data.test")

Ext.ns("panel.admin")
Ext.ns("form.admin")
Ext.ns("window.admin")
Ext.ns("tree.admin")
Ext.ns("grid.admin")

Ext.ns("panel.xf")
Ext.ns("form.xf")
Ext.ns("window.xf")
Ext.ns("grid.xf")

//EOP
;/**
 * 用户组维护
 */
panel.admin.GroupGridPanel = Ext.extend(divo.panel.SmartGridDetailPanel, {
	initComponent : function() {
 		this.action = new Ext.ux.grid.RowActions({
            header:'操作',
            autoWidth:false, 
            width:60,
            actions:[{
                iconCls:'icon-update',
                tooltip:'修改用户组',
                hideIndex: this.canUpdate()?false:'update_not_allowed',
                hide: !this.canUpdate()
            },{
                iconCls:'icon-delete',
                tooltip:'删除用户组',
                hideIndex:!this.canDelete()?false:'delete_note_allowed',
                hide: !this.canDelete()
            }]
        })
		this.action.on('action',this.onAction,this)
	
		Ext.apply(this, {
			url : "/groups",
			fieldDefinitions : this.getListDefinitions(),
			gridConfig : {
				gridIdOfView : 'admin-group-grid', 
				filter : false,
				footerSimple : true,
				toolbar : this.isLookup?false:this.createToolbarBtn(),
				plugins : [this.action],
				autoExpandColumn : 'name'
			},
			dialogTitle : "新建/修改 用户组",
			dialogWidth : 400,
			dialogHeight : 200,
			autoScroll : true
		})
		this.form = this.createForm()
		
		panel.admin.GroupGridPanel.superclass.initComponent.apply(this,arguments)
	},
	onAction : function(grid, record, action, row, col) {
		if (action=='icon-update')
		    this.editItem()
		if (action=='icon-delete')
		    this.deleteItem()
	},
	//重写
	createGridMeta : function() {
		return this.getGridMeta(this.fieldDefinitions,this.isLookup?null:[this.action])
	},
	getListDefinitions : function() {
		return [{
			name : 'id'
		},{
			name : 'name',
			header : '名称',
			searchable : true,
			type : 'string',
			id : 'name'
		},{
			name : 'update_not_allowed',
			type : 'bool',
			convert : function(v,rec) {
				return rec.id == 1 
			}
		},{
			name : 'delete_note_allowed',
			type : 'bool',
			convert : function(v,rec) {
				return rec.id == 1
			}
		}]
	},
	createForm : function() {
		return new divo.form.DivoForm({
			formType : "editOnly",
			showButtons : false,
			showTitle : false,
			alternateRows : false,
			labelClass : "label",
			fieldDefinitions : this.getFormDefinitions()
		})
	},
	getFormDefinitions : function() {
		return ([{
			field : "name",
			label : "名称",
			required : true
		}]);
	},
	// 添加工具条按钮
	createToolbarBtn : function(){
		var tb = [];

		var addBtn = new Ext.Toolbar.Button( {
			text : '新建',
			tooltip : '新建用户组',
			icon : divo.iconAdd,
			cls : 'x-btn-text-icon',
			handler : this.addItem.createDelegate(this),
			hidden : !this.canCreate()
		})
		tb.push(addBtn)
		return tb
	},
	onLoadItem : function(id) {
		Ext.Ajax.request({
			scope : this,
			url : this.url+'/'+id,
			method : 'GET',
			success : function(response, options) {
				var resp = Ext.decode(response.responseText);
				this.fillForm(resp.data)
			},
			failure : function(response, options) {
				this.alert(response.responseText);
			}
		})
	},
	onSaveItem : function(item) {
		this.form.clearErrorMessages()
		var adding = !item.id
		this.sayWait("保存")
		
		Ext.Ajax.request({
			scope : this,
			url : this.url+(adding ? '' : '/'+item.id),
			method : adding ? 'POST':'PUT',
			jsonData : item,
			success : function(response, options) {
				var resp = Ext.decode(response.responseText)
				this.saveItemCallback(adding,resp)				
			},
			failure : function(response, options) {
				this.alert(response.responseText)
			}
		})
	},
	onDeleteItem : function(id) {
		Ext.Ajax.request({
			scope : this,
			url : this.url+'/'+id,
			method : 'DELETE',
			success : function(response, options) {
				var resp = Ext.decode(response.responseText)
				if (resp.success)
					this.deleteItemCallback()
				else
				    this.say(resp.errors.reason) 
			},
			failure : function(response, options) {
				this.alert(response.responseText)
			}
		})
	}

})

Ext.reg('panel.admin.GroupGridPanel', panel.admin.GroupGridPanel);
// EOP

;/**
 * 用户组对应的全局权限管理
 */
panel.admin.GroupGlobalPermissionsGridPanel = Ext.extend(divo.panel.SmartGridPanel, {
	initComponent : function() {
 		this.action = new Ext.ux.grid.RowActions({
            header:'',
            actions:[{
                iconCls:'icon-delete',
                tooltip:'删除此权限',
                hide : !this.canDelete()
            }]
        })
		this.action.on('action',this.onAction,this)
	
		Ext.apply(this, {
			fieldDefinitions : this.getListDefinitions(),
			gridConfig : {
				gridIdOfView : 'admin-group-globals-grid',
				toolbar : this.createToolbarBtn(),
				plugins : [this.action],
				footer : false,
				displayLoadMask : false,
				autoExpandColumn : 'descrip'
			},
			autoScroll : true
		})
		
		this.subscribe("window.admin.GroupGlobalPermissionsChanged",this.onGroupGlobalPermissionsChanged,this)
		this.on('beforedestroy',function() {
		      this.unsubscribe()
		},this)
		
		panel.admin.GroupGlobalPermissionsGridPanel.superclass.initComponent.apply(this,arguments)
	},
	onAction : function(grid, record, action, row, col) {
		if (action=='icon-delete')
		    this.deletePermission(record.data.id)
	},
	//重写
	createGridMeta : function() {
		return this.getGridMeta(this.fieldDefinitions,this.isLookup?null:[this.action])
	},
	getListDefinitions : function() {
		return [{
			name : 'id'
		},{
			name : 'name',
			header : '名称',
			type : 'string'
		},{
			name : 'descrip',
			header : '描述',
			type : 'string',
			id : 'descrip'
		}]
	},
	// 添加工具条按钮
	createToolbarBtn : function(){
		var tb = [];

		var addBtn = new Ext.Toolbar.Button( {
			text : '选择',
			tooltip : '新增或删除全局权限',
			icon : divo.iconAdd,
			cls : 'x-btn-text-icon',
			hidden : !this.canCreate() && !this.canUpdate(),
			handler : this.selectPermissions.createDelegate(this)
		})
		tb.push(addBtn)
		return tb
	},
	selectPermissions : function() {
		if (!this.validate()) {
			return
		}
		this.groupGlobalPermissionWindowId = this.myId('win')
		
		var win = new window.admin.GroupGlobalPermissionWindow({
			id : this.groupGlobalPermissionWindowId,
			closeAction : "destroy",
			cancelAction : "destroy",
			groupId : this.groupId,
			groupName : this.getGroupName()
		})
		win.show()
	},
	onGroupGlobalPermissionsChanged : function(subj, msg, data) {
		if (msg.sender==this.groupGlobalPermissionWindowId) {
			this.showList()
		}
	},
	deletePermission : function(id) {
		if (!this.validate()) {
			return
		}
		var ok = true
		Ext.Ajax.request({
			scope : this,
			url : "/groups/"+this.groupId+"/permissions/global/"+id,
			async : false,
			method : 'DELETE',
			success : function(response, options) {
				var resp = Ext.decode(response.responseText)
				if (!resp.success) {
					ok = false
				    this.say(resp.errors.reason)
				}     
			},
			failure : function(response, options) {
				this.alert(response.responseText)
				ok = false
			}
		});
		if (ok) {
			this.showList()
		}
	},
	validate : function() {
		if (!this.groupId) {
			this.say("请选择用户组")
			return false
		}
		if (this.groupId == 1) {
			this.say("系统管理用户组不允许变动全局权限")
			return false
		}
		return true
	},
	//public
	showList : function(groupId) {
	   if (groupId)
	   	   this.groupId = groupId
	   
	   if (!this.groupId) return
	   
	   this.setUrl("/groups/"+this.groupId+"/permissions/global")
  	   this.loadList()
	},
	getGroupName : function() {
		var name = ''
		Ext.Ajax.request({
			scope : this,
			url : "/groups/"+this.groupId,
			async : false,
			method : 'GET',
			success : function(response, options) {
				var resp = Ext.decode(response.responseText)
				if (!resp.success) {
					this.say(resp.errors.reason)
					return
				}
				name = resp.data.name
			},
			failure : function(response, options) {
				this.alert(response.responseText)
			}
		})
		return name
	}
})

Ext.reg('panel.admin.GroupGlobalPermissionsGridPanel', panel.admin.GroupGlobalPermissionsGridPanel);
// EOP

;/**
 * 选择全局权限表单
 */
form.admin.GroupGlobalPermissionForm = Ext.extend(Ext.form.FormPanel, {
	groupId : null,
	initComponent : function() {
		
		Ext.apply(this, {
			baseCls : "x-plain",
			labelWidth : 75,
			labelAlign : "right",
			autoScroll : true,
			bodyStyle : "padding:0",
			items : [{
				xtype : "itemselector",
				name : 'group_global',
				hideLabel : true,
				fromStore:this.getFromDataStore(),
				toStore:this.getToDataStore(),
				msWidth:250,
				msHeight:200,
				valueField : "id",
				displayField : "descrip",
				toLegend:"已选",
				fromLegend:"候选",
				drawUpIcon:false,
				drawDownIcon:false,
				drawTopIcon:false,
				drawBotIcon:false
			}]
		});

		form.admin.GroupGlobalPermissionForm.superclass.initComponent.call(this);
	},
	// 保存选择的全局权限
	save : function(callbackOnSuccess) {	
		var itemStr = this.getForm().getObjectValues()
		if (itemStr.group_global.length>0)
		    var items = itemStr.group_global
		else    
		    var items = null 

		//删除现有全部全局权限
		if (!this.deleteAll()) return
		
		//存入新的全局权限
		var ok = true
		if (items) {
		    ok = this.saveAll(items)
		}
		if (ok) {
			this.say("选择的全局权限已经保存")
			callbackOnSuccess.call()
		}
	},
	getFromDataStore : function() {
		return new Ext.data.Store({					 
			autoLoad: true,
			proxy : new Ext.data.HttpProxy( {
				method : 'GET',
				url : "/groups/"+this.groupId+"/permissions/global/avaiable"
			}),
			reader: this.getReader(),
			sortInfo:{field:'descrip', direction:'ASC'}
		})		
	},
	getToDataStore : function() {
		return new Ext.data.Store({					 
			autoLoad: true,
			proxy : new Ext.data.HttpProxy( {
				method : 'GET',
				url : "/groups/"+this.groupId+"/permissions/global"
			}),
			reader: this.getReader(),
			sortInfo:{field:'descrip', direction:'ASC'}
		})		
	},
	getReader : function() {
		return new Ext.data.JsonReader({
			idProperty:'id',
			root:'rows',
			fields: [
				{name: 'id', type: 'int'},
				{name: 'descrip', type: 'string'}
			]
		})		
	},
	deleteAll : function() {
		var ok = true
		Ext.Ajax.request({
			scope : this,
			url : "groups/"+this.groupId+"/permissions/global",
			async : false,
			method : 'DELETE',
			success : function(response, options) {
				var resp = Ext.decode(response.responseText)
				if (!resp.success) {
					ok = false
				    this.say(resp.errors.reason)
				}     
			},
			failure : function(response, options) {
				this.alert(response.responseText)
				ok = false
			}
		});
		return ok
	},
	saveAll : function(items) {
		var ok = true
		Ext.Ajax.request({
			scope : this,
			url : "groups/"+this.groupId+"/permissions/global",
			async : false,
			method : 'POST',
			jsonData : {idList:items}, //用逗号分隔的id值列表
			failure : function(response, options) {
				this.alert(response.responseText)
				ok = false
			}
		});
		return ok
	}
});

Ext.reg("form.admin.GroupGlobalPermissionForm", form.admin.GroupGlobalPermissionForm);
// EOP

;/**
 * 用户组对应的全局权限维护窗口
 * 
 * --------------------------------------------------------------
 * 消息：
 * 用户组对应的全局权限有了变动
 * 
 * 消息名：     			
 * window.admin.GroupGlobalPermissionsChanged  
 * 
 * 消息内容：
 * {int} sender 当前组件Id
 * --------------------------------------------------------------
 * 
 */
window.admin.GroupGlobalPermissionWindow = Ext.extend(Ext.Window, {
	cancelAction : "hide",  //还可以取值：destroy
	closeAction : "hide",
	groupId : null,
	groupName : null,
	initComponent : function() {
		Ext.apply(this,{
			title : '选择全局权限 - '+this.groupName,
			width : 550,	
			height : 300,
			modal : true,
			closable : true,
			maximizable : false,
			minimizable : false,
			layout : "fit",
			buttons : [{
				text : "确定",
				handler : this.onSave,
				scope : this
			}, {
				text : "取消",
				handler : this.onCancel,
				scope : this
			}],
			items : {
				xtype : "form.admin.GroupGlobalPermissionForm",
				groupId : this.groupId
			}
		});
		
		window.admin.GroupGlobalPermissionWindow.superclass.initComponent.call(this);
	},
	onSave : function() {
		this.items.itemAt(0).save(this.onSaveSucccess.createDelegate(this))
	},
	onSaveSucccess : function() {
		this.close()
		this.publish("window.admin.GroupGlobalPermissionsChanged",{sender:this.id})
	}
});
// EOP

;/**
 * 用户组对应的菜单项权限管理
 */
panel.admin.GroupFunctionalPermissionsGridPanel = Ext.extend(divo.panel.SmartGridPanel, {
	initComponent : function() {
 		this.action = new Ext.ux.grid.RowActions({
            header:'',
            actions:[{
                iconCls:'icon-update',
                tooltip:'修改此权限',
                hide : !this.canUpdate()
            },{
                iconCls:'icon-delete',
                tooltip:'删除此权限',
                hide : !this.canDelete()
            }]
        })
		this.action.on('action',this.onAction,this)
	
		Ext.apply(this, {
			fieldDefinitions : this.getListDefinitions(),
			gridConfig : {
				gridIdOfView : 'admin-group-functionals-grid',
				toolbar : this.createToolbarBtn(),
				plugins : [this.action],
				footer : false,
				displayLoadMask : false,
				autoExpandColumn : 'name'
			},
			autoScroll : true
		})
		
		this.subscribe("window.admin.GroupFunctionalPermissionsChanged",this.onGroupFunctionalPermissionsChanged,this)
		this.on('beforedestroy',function() {
		      this.unsubscribe()
		},this)
		
		panel.admin.GroupFunctionalPermissionsGridPanel.superclass.initComponent.apply(this,arguments)
	},
	onAction : function(grid, record, action, row, col) {
		if (action=='icon-delete')
		    this.deletePermission(record.data.id)
		if (action=='icon-update')
		    this.editPermission(record.data.id,record.data.permission)
	},
	//重写
	createGridMeta : function() {
		return this.getGridMeta(this.fieldDefinitions,this.isLookup?null:[this.action])
	},
	getListDefinitions : function() {
		return [{
			name : 'id'
		},{
			name : 'name',
			header : '名称',
			type : 'string',
			id : 'name'
		},{
			name : 'permission',
			type : 'int'
		},{
			header : '全部',
			name : 'p_all',
			type : 'bool',
			convert : function(v,rec) {
				return rec.permission == 7
			},
			renderer : this.permissionRender.createDelegate(this)
		},{
			header : '只读',
			name : 'p_read',
			type : 'bool',
			convert : function(v,rec) {
				return rec.permission == 0
			},
			renderer : this.permissionRender.createDelegate(this)
		},{
			header : '新建',
			name : 'p_new',
			type : 'bool',
			convert : function(v,rec) {
				return rec.permission == 1
			},
			renderer : this.permissionRender.createDelegate(this)
		},{
			header : '修改',
			name : 'p_edit',
			type : 'bool',
			convert : function(v,rec) {
				return rec.permission == 2
			},
			renderer : this.permissionRender.createDelegate(this)
		},{
			header : '删除',
			name : 'p_delete',
			type : 'bool',
			convert : function(v,rec) {
				return rec.permission == 4
			},
			renderer : this.permissionRender.createDelegate(this)
		}]
	},
	permissionRender : function(value, p, record) {
		if (value)
			return '<img src="media/images/divo/publish.gif"/>'
		return ""
	},
	// 添加工具条按钮
	createToolbarBtn : function(){
		var tb = [];

		var addBtn = new Ext.Toolbar.Button( {
			text : '添加',
			tooltip : '新增或删除菜单使用权限',
			icon : divo.iconAdd,
			cls : 'x-btn-text-icon',
			hidden : !this.canCreate() && !this.canUpdate(),
			handler : this.addPermission.createDelegate(this)
		})
		tb.push(addBtn)
		return tb
	},
	addPermission : function() {
		if (!this.groupId) {
			this.say("请选择用户组")
			return
		}
		this.groupFunctionalPermissionWindowId = this.myId('win')
		
		var win = new window.admin.GroupFunctionalPermissionWindow({
			id : this.groupFunctionalPermissionWindowId,
			closeAction : "destroy",
			cancelAction : "destroy",
			groupId : this.groupId,
			groupName : this.getGroupName()
		})
		win.show()
	},
	editPermission : function(menuItemId,permission) {
		if (!this.validate()) {
			return
		}
		this.groupFunctionalPermissionWindowId = this.myId('win')
		
		var win = new window.admin.GroupFunctionalPermissionWindow({
			id : this.groupFunctionalPermissionWindowId,
			closeAction : "destroy",
			cancelAction : "destroy",
			groupId : this.groupId,
			groupName : this.getGroupName(),
			menuItemId : menuItemId,
			permission : permission
		})
		win.show()
	},
	onGroupFunctionalPermissionsChanged : function(subj, msg, data) {
		if (msg.sender==this.groupFunctionalPermissionWindowId) {
			this.showList()
		}
	},
	deletePermission : function(id) {
		if (!this.validate()) {
			return
		}
		var ok = true
		Ext.Ajax.request({
			scope : this,
			url : "/groups/"+this.groupId+"/permissions/functional/"+id,
			async : false,
			method : 'DELETE',
			success : function(response, options) {
				var resp = Ext.decode(response.responseText)
				if (!resp.success) {
					ok = false
				    this.say(resp.errors.reason)
				}     
			},
			failure : function(response, options) {
				this.alert(response.responseText)
				ok = false
			}
		});
		if (ok) {
			this.showList()
		}
	},
	validate : function() {
		if (!this.groupId) {
			this.say("请选择用户组")
			return false
		}
		if (this.groupId == 1) {
			this.say("系统管理用户组不允许变动菜单使用权限")
			return false
		}
		return true
	},
	//public
	showList : function(groupId) {
	   if (groupId)
	   	   this.groupId = groupId
	   
	   if (!this.groupId) return
	   
	   this.setUrl("/groups/"+this.groupId+"/permissions/functional")
  	   this.loadList()
	},
	getGroupName : function() {
		var name = ''
		Ext.Ajax.request({
			scope : this,
			url : "/groups/"+this.groupId,
			async : false,
			method : 'GET',
			success : function(response, options) {
				var resp = Ext.decode(response.responseText)
				if (!resp.success) {
					this.say(resp.errors.reason)
					return
				}
				name = resp.data.name
			},
			failure : function(response, options) {
				this.alert(response.responseText)
			}
		})
		return name
	}
})

Ext.reg('panel.admin.GroupFunctionalPermissionsGridPanel', panel.admin.GroupFunctionalPermissionsGridPanel);
// EOP

;/**
 * 指定用户组可以使用的候选菜单项
 */
panel.admin.GroupAvaiableFunctionalPermissionsGridPanel = Ext.extend(divo.panel.SmartGridPanel, {
	groupId : null,
	initComponent : function() {
		Ext.apply(this, {
			url : "/groups/"+this.groupId+"/permissions/functional/avaiable", 
			fieldDefinitions : this.getListDefinitions(),
			gridConfig : {
				gridIdOfView : 'admin-group-functionals-avaiable-grid',
				filter : true,
				footerSimple : true,
				showTooltip : true
			}
		})
	
		panel.admin.GroupAvaiableFunctionalPermissionsGridPanel.superclass.initComponent.apply(this,arguments)
	},
	getListDefinitions : function() {
		return [{
			name : 'id'
		},{
			name : 'name',
			header : '名称',
			searchable : true,
			type : 'string'
		},{
			name : 'descrip',
			header : '描述',
			searchable : true,
			type : 'string'
		}]
	}
})

Ext.reg('panel.admin.GroupAvaiableFunctionalPermissionsGridPanel', panel.admin.GroupAvaiableFunctionalPermissionsGridPanel);
// EOP
;/**
 * 为用户组添加或修改菜单项使用权限表单
 */
form.admin.GroupFunctionalPermissionForm = Ext.extend(Ext.form.FormPanel, {
	groupId : null,
	menuItemId : null, //修改时传递此id
	permission : null,
	initComponent : function() {
		
		this.getMenuItem()
		
		var lovDisplay = [divo.t1 + '{name}' + divo.t2].join('')
		this.menuItemFld = {
			xtype : 'xlovfield',
			name : 'itemId',
			fieldLabel : '菜单项',
			allowBlank : true,
			multiSelect : false,
			lovTitle : '请选择',
			lovHeight : 350,
			lovWidth : 450,
			minItem : 1,
			maxItem : 1,
			width : 200,
			disabled : this.menuItemId?true:false,
			valueField : 'id',
			displayField : lovDisplay,
			displayValue : this.menuItem?this.menuItem.name:'',
			hiddenValue : this.menuItem?this.menuItem.id:'',
			textarea : false,
			showOnFocus : true,
			view : new panel.admin.GroupAvaiableFunctionalPermissionsGridPanel({
					isLookup:true,
					groupId : this.groupId
			})
		}
		
		this.permissionFld = {
			xtype : "ux-radiogroup",
			fieldLabel : "操作权限",
			name : "permission",
			anchor : "100%",
			horizontal : true,
			radios : [{
				value : 7,
				boxLabel : "全部",
				checked : this.permission?this.permission==7:true
			}, {
				value : 0,
				boxLabel : "只读",
				checked : this.permission?this.permission==0:false
			}, {
				value : 1,
				boxLabel : "新建",
				checked : this.permission?this.permission==1:false
			}, {
				value : 2,
				boxLabel : "修改",
				checked : this.permission?this.permission==2:false
			}, {
				value : 4,
				boxLabel : "删除",
				checked : this.permission?this.permission==4:false
			}]		
		}		
				
		Ext.apply(this, {
			labelWidth : 100,
			defaultType : "textfield",
			labelAlign : "right",
			autoScroll : true,
			bodyStyle : "padding:10px",
			items : [this.menuItemFld,this.permissionFld]
		});

		form.admin.GroupFunctionalPermissionForm.superclass.initComponent.call(this);
	},
	getMenuItem : function() {
		if (!this.menuItemId) return
		
		Ext.Ajax.request({
			scope : this,
			url : "/menus/items/"+this.menuItemId,
			async : false,
			method : 'GET',
			success : function(response, options) {
				var resp = Ext.decode(response.responseText)
				if (!resp.success) {
					this.say(resp.errors.reason)
					return
				}
				this.menuItem = resp.data
			},
			failure : function(response, options) {
				this.alert(response.responseText)
			}
		})
	},
	// public
	clearContent : function() {
		this.getForm().reset()

		var fld = this.getForm().findField("itemId")
		fld.setNameValue('','')
	},
	// public
	save : function(callbackOnSuccess) {
		var item = this.getForm().getObjectValues()
		if (!item.itemId) {
			this.say("请选择菜单项")
			return
		}
		
		Ext.Ajax.request({
			scope : this,
			url : "groups/" + this.groupId + "/permissions/functional",
			waitMsg : "正在提交...",
			method : this.menuItemId?'PUT':'POST',
			jsonData : item,
			success : function(response, options) {
				var resp = Ext.decode(response.responseText);
				if (!resp.success) {
					this.say(resp.errors.reason)
				} else {
					callbackOnSuccess.call()
				}
			},
			failure : function(response, options) {
			    this.alert(response.responseText)
			}
		});
	}
});

Ext.reg("form.admin.GroupFunctionalPermissionForm", form.admin.GroupFunctionalPermissionForm);
// EOP

;/**
 * 用户组对应的菜单使用权限维护窗口
 * 
 * --------------------------------------------------------------
 * 消息：
 * 用户组对应的菜单使用权限有了变动
 * 
 * 消息名：     			
 * window.admin.GroupFunctionalPermissionsChanged   
 * 
 * 消息内容：
 * {int} sender 当前组件Id
 * --------------------------------------------------------------
 * 
 */
window.admin.GroupFunctionalPermissionWindow = Ext.extend(Ext.Window, {
	cancelAction : "hide",  //还可以取值：destroy
	closeAction : "hide",
	groupId : null,
	groupName : null,
	menuItemId : null,  //修改时传递此id
	permission : null,
	initComponent : function() {
		Ext.apply(this,{
			title : '添加/修改 菜单使用权限 - '+this.groupName,
			width : 450,	
			height : 250,
			modal : true,
			stateful : true,
			stateId : 'admin-group-functional-permission-win',
			closable : true,
			maximizable : false,
			minimizable : false,
			layout : "fit",
			buttons : [{
				text : "确定",
				handler : this.onSave,
				scope : this
			}, {
				text : "取消",
				handler : this.onCancel,
				scope : this
			}],
			items : {
				xtype : "form.admin.GroupFunctionalPermissionForm",
				groupId : this.groupId,
				menuItemId : this.menuItemId,
				permission : this.permission
			}
		});
		
		window.admin.GroupFunctionalPermissionWindow.superclass.initComponent.call(this);
	},
	onSave : function() {
		this.items.itemAt(0).save(this.onSaveSucccess.createDelegate(this))
	},
	onSaveSucccess : function() {
		if (this.menuItemId) {
			this.close()
		} else {	
		    this.say("新添加的菜单项权限已保存，请继续添加。")
		    this.items.itemAt(0).clearContent()
		}    
		
		this.publish("window.admin.GroupFunctionalPermissionsChanged",{sender:this.id})
	}
});
// EOP

;/**
 * 菜单维护
 */
divo.admin.menu.MainPanel = Ext.extend(Ext.Panel, {
	initComponent : function() {
		this.menuTreeId = this.myId('tree')
		this.menuItemsPanelId = this.myId('menu-items')
		this.menuItemsAvaiablePanelId = this.myId('menu-items-avaiable')

		Ext.apply(this, {
			layout : 'tdgi_border',
			defaults : {
				border : false
			},
			border : false,
			items : [{
				stateful : true,
				stateId : this.myId('menu'),
				region : 'west',
				layout : 'fit',
				title : '菜单树',
				collapsible : false,
				ctCls : "j-toolbar-dark",
				width : 300,
				collapsedTitle : false,
				split : true,
				items : [{
					id : this.menuTreeId,
					xtype : "tree.admin.MenuTree",
					menuItemId : this.menuItemId
				}]
			}, {
				stateful : true,
				stateId : this.myId('items-avaiable'),
				region : 'east',
				layout : 'fit',
				title : '候选菜单项',
				collapsible : true,
				ctCls : "j-toolbar-dark",
				width : 400,
				collapsedTitle : true,
				split : true,
				items : [{
					id : this.menuItemsAvaiablePanelId,
					xtype : "panel.admin.MenuAvaiableItemsGridPanel",
					menuItemId : this.menuItemId
				}]
			}, {
				region : 'center',
				layout : 'fit',
                autoScroll:true,
				title : '对应菜单项',
				ctCls : "j-toolbar-dark",
				items : [{
					id : this.menuItemsPanelId,
					xtype : "grid.admin.MenuItemsGrid",
					menuItemId : this.menuItemId
				}]
			}]	
		})
		
		this.subscribe("j.tree.nodeSelect",this.onMenuSelected,this)
		this.subscribe("tree.admin.MenuItemsSorted",this.onMenuItemsSorted,this) 
		this.subscribe("grid.admin.MenuItemsDeleted",this.onMenuItemsDeleted,this)
		this.subscribe("panel.admin.MenuItemsAdded",this.onMenuItemsAdded,this)
		this.on('beforedestroy',function() {
		      this.unsubscribe()
		},this)

		divo.admin.menu.MainPanel.superclass.initComponent.call(this)
	},
	//选择了菜单树节点
	onMenuSelected : function(subj, msg, data) {
		if (msg.sender==this.menuTreeId) {
			if (msg.node.attributes.codeLevel==4) { 
			    Ext.getCmp(this.menuItemsPanelId).refresh(msg.node.id)
			    Ext.getCmp(this.menuItemsAvaiablePanelId).showList(msg.node.id)
			}
		}
	},
	//菜单对应菜单项排序了
	onMenuItemsSorted : function(subj, msg, data) {
		if (msg.sender==this.menuTreeId) {
	    	Ext.getCmp(this.menuItemsPanelId).refresh(msg.node.id)
		}	
	},
	//菜单对应菜单项被删除了
	onMenuItemsDeleted : function(subj, msg, data) {
		if (msg.sender==this.menuItemsPanelId) {
		    Ext.getCmp(this.menuItemsAvaiablePanelId).showList(msg.menuId)
		}	
	},
	//添加了菜单对应的菜单项
	onMenuItemsAdded : function(subj, msg, data) {
		if (msg.sender==this.menuItemsAvaiablePanelId) {
	    	Ext.getCmp(this.menuItemsPanelId).refresh(msg.menuId)
		}	
	}
})

divo.admin.menu.Main = function() {
	/* ----------------------- private变量 ----------------------- */

	/* ----------------------- private方法 ----------------------- */
	// 创建布局
	function createLayout(parentPanel,menuItemId) {
		parentPanel.add(new divo.admin.menu.MainPanel({
			id : 'admin-menu',
			menuItemId : menuItemId
		}))
		parentPanel.doLayout()
	}

	/* ----------------------- public方法 ----------------------- */
	return {

		// 初始化
		init : function(parentPanel, menuItemId) {
			createLayout(parentPanel,menuItemId)
		}

	} // return

}()
// EOP

;/**
 * 菜单树维护
 * 
 * -------------------------------------------------------------- 消息：
 * 菜单对应的菜单项排序成功
 * 
 * 消息名： tree.admin.MenuItemsSorted
 * 
 * 消息内容： {int} sender 当前组件Id {Ext.tree.TreeNode} node 当前菜单节点对象
 * --------------------------------------------------------------
 * 
 */
tree.admin.MenuTree = Ext.extend(divo.tree.DynamicTree, {
	initComponent : function() {
		this.addOrEditWinId = this.myId("add-edit-win")

		Ext.apply(this, {
			url : '/menus/children',
			rootUrl : '/menus/root',
			nodeConfigFn : this.createMyNode,
			treeName : '菜单'
		})

		this.subscribe("window.admin.MenuChanged", this.onTreeMainted, this)
		this.subscribe("window.admin.MenuOrderChanged",
				this.onTreeOrderChanged, this)
		this.on('beforedestroy', function() {
			this.unsubscribe()
		}, this)

		tree.admin.MenuTree.superclass.initComponent.call(this)
	},
	// 当菜单新建\修改后
	onTreeMainted : function(subj, msg, data) {
		if (msg.sender == this.addOrEditWinId) {
			if (msg.parentNode.reload)
				msg.parentNode.reload()
			else
				msg.parentNode.parentNode.reload()
		}
	},
	// 当菜单或菜单项排序后
	onTreeOrderChanged : function(subj, msg, data) {
		if (msg.sender == this.menuSortWinId) {
			if (msg.node.reload)
				msg.node.reload()
			else
				// 对应菜单项排序了
				this.publish("tree.admin.MenuItemsSorted", {
					sender : this.id,
					node : msg.node
				})
		}
	},
	// 构造树节点
	createMyNode : function(data) {
		return {
			leaf : data.is_leaf,
			id : data.id,
			text : data.name,
			codeLevel : data.code_level,
			parentId : data.parent_id,
			draggable : data.parent_id > 0
		}
	},
	onAdd : function(node) {
		if (node.attributes.codeLevel == 1) {
			this.say("目前只允许一个工作区")
			return
		}
		if (node.attributes.codeLevel == 4) {
			this.say("只能创建[工作区-模块-主菜单]三级菜单")
			return
		}
		var win = new window.admin.MenuAddOrEditWindow({
			id : this.addOrEditWinId,
			closeAction : "destroy",
			cancelAction : "destroy",
			menuParentNode : node
		})
		win.show()
	},
	onUpdate : function(node) {
		var win = new window.admin.MenuAddOrEditWindow({
			id : this.addOrEditWinId,
			closeAction : "destroy",
			cancelAction : "destroy",
			menuParentNode : node.parentNode,
			menuName : node.text,
			menuId : node.id
		})
		win.show()
	},
	onDelete : function(node) {
		if (node.id == this.root.id) {
			this.say('根节点不允许删除。')
			return
		}
		if (node.id == 2) {
			this.say('默认工作区不允许删除。')
			return
		}
		if (node.id == 3) {
			this.say('默认模块不允许删除。')
			return
		}
		if (node.firstChild) {
			this.say('还有子节点，不允许删除。')
			return
		}
		if (this.isMainMenuNodeAndHasItems(node)) {
			this.say('已经有对应菜单项，不允许删除。')
			return
		}
		this.currentNode = node
		Ext.MessageBox.confirm('确认', '要删除吗？', this.deleteConfirm
				.createDelegate(this))
	},
	deleteConfirm : function(btn) {
		if (btn !== 'yes')
			return

		var ok = true
		var node = this.currentNode
		Ext.Ajax.request({
			scope : this,
			url : "/menus/" + node.id,
			async : false,
			method : 'DELETE',
			success : function(response, options) {
				var resp = Ext.decode(response.responseText)
				if (!resp.success) {
					ok = false
					this.say(resp.errors.reason)
				}
			},
			failure : function(response, options) {
				this.alert(response.responseText)
				ok = false
			}
		});
		if (ok)
			node.parentNode.removeChild(node)

	},
	// 返回值为false，表示不允许拖动
	onChangeNodeParent : function(node, oldParentNode, newParentNode) {
		if (newParentNode.id == this.root.id) {
			this.say("目前只允许一个工作区")
			return false
		}
		if (node.id == 2) {
			this.say('默认工作区不允许移动。')
			return false
		}
		if (node.id == 3) {
			this.say('默认模块不允许移动。')
			return false
		}
		if (this.isMainMenuNodeAndHasItems(node)
				&& newParentNode.attributes.codeLevel < 3) {
			this.say('已经有对应菜单项，只能移动到其他模块。')
			return false
		}
		Ext.Ajax.request({
			scope : this,
			url : "/menus/" + node.id + "/parent",
			async : false,
			method : 'PUT',
			jsonData : {
				newParentId : newParentNode.id
			},
			success : function(response, options) {
				var resp = Ext.decode(response.responseText)
				if (resp.success) {
					this.say('拖动后保存成功')
				}
			},
			failure : function(response, options) {
				this.alert(response.responseText)
			}
		})
		return true
	},
	onChangeDisplayOrder : function(node) {
		if (node.attributes.codeLevel < 4 && !node.firstChild) {
			this.say("无子节点，不能进行排序操作")
			return
		} // 主菜单一级的下级节点为对应菜单项
		this.menuSortWinId = this.myId('sort-win')
		var win = new window.admin.MenuSortWindow({
			id : this.menuSortWinId,
			closeAction : "destroy",
			cancelAction : "destroy",
			menuParentNode : node
		})
		win.show()
	},
	isMainMenuNodeAndHasItems : function(node) {
		if (node.attributes.codeLevel < 4)
			return false

		var ok = true
		var count = 0
		Ext.Ajax.request({
			scope : this,
			url : "/menus/" + node.id + "/items",
			async : false,
			method : 'GET',
			success : function(response, options) {
				var resp = Ext.decode(response.responseText)
				count = resp.totalCount
			},
			failure : function(response, options) {
				this.alert(response.responseText)
				ok = false
			}
		});
		return ok && count > 0
	}
})

Ext.reg("tree.admin.MenuTree", tree.admin.MenuTree);
// EOP

;/**
 * 菜单新建或修改表单
 */
form.admin.MenuAddOrEditForm = Ext.extend(Ext.form.FormPanel, {
	menuParentId : null,
	menuParentName : null,
	menuName : null,
	menuId : null,
	initComponent : function() {
		
		Ext.apply(this, {
			labelWidth : 100,
			defaultType : "textfield",
			labelAlign : "right",
			autoScroll : true,
			bodyStyle : "padding:10px",
			layout : 'autotableform',
			items : [{
				xtype : 'formHtml',
				fieldLabel : "上级节点",
				anchor : "100%",
				value : this.menuParentName
			}, {
				fieldLabel : "名称",
				name : "name",
				anchor : "100%",
				value : this.menuName || ''
			}, {
				xtype: 'hidden',
				name : 'parent_id',
				value : this.menuParentId || 0
			}]
		});

		form.admin.MenuAddOrEditForm.superclass.initComponent.call(this);
	},
	//public
	save : function(callbackOnSuccess) {
		var item = this.getForm().getObjectValues()
		
		Ext.Ajax.request({
			scope : this,
			url : "/menus" + (this.menuId?"/"+this.menuId:""),
			waitMsg : "正在提交...",
			method : this.menuId?'PUT':'POST',
			jsonData : item,
			success : function(response, options) {
				var resp = Ext.decode(response.responseText);
				if (!resp.success) {
					this.getForm().markInvalid(resp.errors)
				} else {
					callbackOnSuccess.call()
				}
			},
			failure : function(response, options) {
			    this.alert(response.responseText)
			}
		});
	}
});

Ext.reg("form.admin.MenuAddOrEditForm", form.admin.MenuAddOrEditForm);
// EOP

;/**
 * 菜单新建或修改窗口
 * 
 * --------------------------------------------------------------
 * 消息：
 * 添加或修改了菜单
 * 
 * 消息名：     			
 * window.admin.MenuChanged 
 * 
 * 消息内容：
 * {int} sender 当前组件Id
 * {Ext.tree.TreeNode} parentNode 被添加或修改菜单的父节点对象
 * --------------------------------------------------------------
 * 
 */
window.admin.MenuAddOrEditWindow = Ext.extend(Ext.Window, {
	cancelAction : "hide",  //还可以取值：destroy
	closeAction : "hide",
	menuParentNode : null,
	menuName : null,
	menuId : null,
	initComponent : function() {
		Ext.apply(this,{
			title : '新建/修改 菜单',
			width : 350,
			height : 180,
			modal : true,
			closable : true,
			maximizable : false,
			minimizable : false,
			layout : "fit",
			buttons : [{
				text : "确定",
				handler : this.onSave,
				scope : this
			}, {
				text : "取消",
				handler : this.onCancel,
				scope : this
			}],
			items : {
				xtype : "form.admin.MenuAddOrEditForm",
				menuParentId : this.menuParentNode.id,
				menuParentName : this.menuParentNode.text,
				menuName : this.menuName,
				menuId : this.menuId
			}
		});
		
		window.admin.MenuAddOrEditWindow.superclass.initComponent.call(this);
	},
	onSave : function() {
		this.items.itemAt(0).save(this.onSaveSucccess.createDelegate(this))
	},
	onSaveSucccess : function() {
		this.close()
		
		this.publish("window.admin.MenuChanged",{
			sender:this.id, 
			parentNode:this.menuParentNode
		})
	}
});
// EOP

;/**
 * 菜单排序表单
 */
form.admin.MenuSortForm = Ext.extend(Ext.form.FormPanel, {
	menuParentNode : null,
	initComponent : function() {
		
		Ext.apply(this, {
			baseCls : "x-plain",
			labelWidth : 75,
			labelAlign : "right",
			autoScroll : true,
			bodyStyle : "padding:0",
			items : [{
				xtype : "itemselector",
				name : 'menu-childs',
				hideLabel : true,
				sorterOnly : true,
				fromStore:this.getFromDataStore(),
				msWidth : 500,
				msHeight : 300,
				valueField : "id",
				displayField : "name"
			}]
		});

		form.admin.MenuSortForm.superclass.initComponent.call(this);

	},
	getFromDataStore : function() {
		if (this.isMenuItemSorter())
			return new Ext.data.Store({					 
				autoLoad: true,
				proxy : new Ext.data.HttpProxy( {
					method : 'GET',
					url : "/menus/" + this.menuParentNode.id + "/items"
				}),
				reader: this.getReader()
			})		
		else
			return new Ext.data.Store({					 
				autoLoad: true,
				proxy : new Ext.data.HttpProxy( {
					method : 'GET',
					url : "/menus/children"
				}),
				reader: this.getReader(),
				baseParams: {
					node:this.menuParentNode.id,
					rootNeeded : 1
				}
			})		
	},
	getReader : function() {
		return new Ext.data.JsonReader({
			idProperty:'id',
			root:'rows',
			fields: [
				{name: 'id', type: 'int'},
				{name: 'name', type: 'string'}
			]
		})		
	},
	//public
	save : function(callbackOnSuccess) {
		var itemStr = this.getForm().findField('menu-childs').getValue()
		var ok = true
		if (this.isMenuItemSorter())
		    var url = "/menus/"+this.menuParentNode.id+"/items/order"
		else
		    var url = "/menus/"+this.menuParentNode.id+"/order" 
		    
		Ext.Ajax.request({
			scope : this,
			url : url,
			async : false,
			method : 'PUT',
			jsonData : {idList:itemStr},
			success : function(response, options) {
				var resp = Ext.decode(response.responseText)
				if (resp.success) 
					this.say('显示顺序修改成功')
			},
			failure : function(response, options) {
				this.alert(response.responseText)
				ok = false
			}
		})
		
		if (ok) callbackOnSuccess.call()
	},
	//真表示对菜单对应菜单项排序
	isMenuItemSorter : function() {
		return this.menuParentNode.attributes.codeLevel==4
	}
});

Ext.reg("form.admin.MenuSortForm", form.admin.MenuSortForm);
// EOP

;/**
 * 菜单排序窗口
 * 
 * --------------------------------------------------------------
 * 消息：
 * 菜单或菜单对应的菜单项排序成功
 * 
 * 消息名：     			
 * window.admin.MenuOrderChanged 
 * 
 * 消息内容：
 * {int} sender 当前组件Id
 * {Ext.tree.TreeNode} node 当前菜单节点对象
 * --------------------------------------------------------------
*/
window.admin.MenuSortWindow = Ext.extend(Ext.Window, {
	cancelAction : "hide",  //还可以取值：destroy
	closeAction : "hide",
	menuParentNode : null,
	initComponent : function() {
		Ext.apply(this,{
			title : '排序',
			width : 540,	
			autoHeight : true,
			layout : "form",
			modal : true,
			closable : true,
			maximizable : false,
			minimizable : false,
			buttons : [{
				text : "确定",
				handler : this.onSave,
				scope : this
			}, {
				text : "取消",
				handler : this.onCancel,
				scope : this
			}],
			items : {
				xtype : "form.admin.MenuSortForm",
				menuParentNode : this.menuParentNode
			}
		});
		
		window.admin.MenuSortWindow.superclass.initComponent.call(this);
	},
	onSave : function() {
		this.items.itemAt(0).save(this.onSaveSucccess.createDelegate(this))
	},
	onSaveSucccess : function() {
		this.close()
		
		this.publish("window.admin.MenuOrderChanged",{
			sender:this.id, 
			node:this.menuParentNode
		})
	}
});
// EOP

;/**
 * 主菜单对应的菜单项网格
 * 
 * --------------------------------------------------------------
 * 消息：
 * 对应的菜单项被删除了
 * 
 * 消息名：     			
 * grid.admin.MenuItemsDeleted 
 * 
 * 消息内容：
 * {int} sender 当前组件Id
 * {int} menuId 当前菜单节点Id
 * --------------------------------------------------------------
 * 
 */
grid.admin.MenuItemsGrid = Ext.extend(divo.grid.SimpleGrid, {
	initComponent : function() {
		Ext.apply(this, {
			fieldDefinitions : this.getListDefinitions(),
			dataStore : this.buildStore()
		});
		grid.admin.MenuItemsGrid.superclass.initComponent.call(this);
	},
	buildStore : function() {
		var cols = [{
			name : "id",
			type : "int"
		}, {
			name : "name",
			type : "string"
		}, {
			name : "descrip",
			type : "string"
		}];
		return new divo.data.ArrayStore({
		   fields : cols
		}) 
	},
	getListDefinitions : function() {
		return ([{
			field : "name",
			label : "名称",
			width : "20%"
		}, {
			field : "descrip",
			label : "描述",
			width : "70%"
		}, {
			field : "action",
			dataType : "action",
			label : "操作",
			sortable : false,
			width : "10%",
			actions : [{
				name : "delete",
				tooltip : '删除与当前菜单对应关系',
				display : '<image src="'+divo.iconDelete+'"/>',
				hidden : !this.canDelete()
			}]
		}]);
	},
	//重写
	onSelectItem : function(view, rowIndex, record, e, action) {
		switch (action) {
			case "delete" :
				this.deleteItem(record);
				break;
			default :
				break;
		}
	},
	// public
	refresh : function(menuId) {
		this.menuId = menuId
		
		Ext.Ajax.request({
			scope : this,
			url : "/menus/" + this.menuId + "/items",
			async : false,
			method : 'GET',
			success : function(response, options) {
				var resp = Ext.decode(response.responseText)
				var arrayData = []
				for (var i = 0; i < resp.totalCount; i++) {
					var data = []
					data.push(resp.rows[i].id)
					data.push(resp.rows[i].name)
					data.push(resp.rows[i].descrip)
					arrayData.push(data)
				}
				this.loadData(arrayData)
			},
			failure : function(response, options) {
				this.alert(response.responseText)
			}
		});
	},
	//删除与当前菜单对应关系
	deleteItem : function(record) {
		var ok = true
		Ext.Ajax.request({
			scope : this,
			url : "/menus/"+this.menuId+"/items/"+record.data.id,
			async : false,
			method : 'DELETE',
			success : function(response, options) {
				var resp = Ext.decode(response.responseText)
				if (!resp.success) {
					ok = false
				    this.say(resp.errors.reason)
				}     
			},
			failure : function(response, options) {
				this.alert(response.responseText)
				ok = false
			}
		})
		if (ok) {
			this.say("删除操作成功")
			this.refresh(this.menuId)
			this.publish("grid.admin.MenuItemsDeleted",{sender:this.id,menuId:this.menuId})
		}
	}

})

Ext.reg("grid.admin.MenuItemsGrid", grid.admin.MenuItemsGrid);
// EOP
;/**
 * 候选菜单项网格
 * 
 * --------------------------------------------------------------
 * 消息：
 * 用户选择了某个菜单项并加入到当前（主）菜单
 * 
 * 消息名：     			
 * panel.admin.MenuItemsAdded    
 * 
 * 消息内容：
 * {int} sender 当前组件Id
 * {int} menuId 菜单Id
 * --------------------------------------------------------------
 * 
 */
panel.admin.MenuAvaiableItemsGridPanel = Ext.extend(divo.panel.SmartGridPanel, {
	initComponent : function() {
 		this.action = new Ext.ux.grid.RowActions({
            header:'操作',
            autoWidth: false,
            width : 100,
            actions:[{
                iconCls:'icon-select',
                tooltip:'添加到当前主菜单',
                hide : !this.canUpdate()
            }]
        })
		this.action.on('action',this.onAction,this)
	
		Ext.apply(this, {
			fieldDefinitions : this.getListDefinitions(),
			gridConfig : {
				gridIdOfView : 'admin-menu-items-avaiable-grid',
				plugins : [this.action],
				footer : false,
				displayLoadMask : false,
				autoExpandColumn : 'name'
			},
			autoScroll : true
		})
		
		panel.admin.MenuAvaiableItemsGridPanel.superclass.initComponent.apply(this,arguments)
	},
	onAction : function(grid, record, action, row, col) {
		if (action=='icon-select')
		    this.selectItem(record.data.id)
	},
	//重写
	createGridMeta : function() {
		return this.getGridMeta(this.fieldDefinitions,this.isLookup?null:[this.action])
	},
	getListDefinitions : function() {
		return [{
			name : 'id'
		},{
			name : 'name',
			header : '名称',
			type : 'string',
			id : 'name'
		}]
	},
	selectItem : function(menuItemId) {
		if (!this.validate()) {
			return
		}
		var ok = true
		Ext.Ajax.request({
			scope : this,
			url : "/menus/"+this.menuId+"/items",
			async : false,
			method : 'POST',
			jsonData : {id:menuItemId},
			success : function(response, options) {
				var resp = Ext.decode(response.responseText)
				if (resp.success) {
					this.say('添加成功')
				}
			},
			failure : function(response, options) {
				this.alert(response.responseText)
				ok = false
			}
		});
		if (ok) {
			this.showList()
			this.publish("panel.admin.MenuItemsAdded",{
				sender:this.id,
				menuId:this.menuId
			})
		}
	},
	validate : function() {
		if (!this.menuId) {
			this.say("请选择主菜单")
			return false
		}
		return true
	},
	//public
	showList : function(menuId) {
	   if (menuId)
	   	   this.menuId = menuId
	   		
	   this.setUrl("/menus/"+this.menuId+"/items/available")
  	   this.loadList()
	}
})

Ext.reg('panel.admin.MenuAvaiableItemsGridPanel', panel.admin.MenuAvaiableItemsGridPanel);
// EOP

;/**
 * 用户帐号信息管理
 */
divo.admin.user.MainPanel = Ext.extend(Ext.Panel, {

	initComponent : function() {
		this.userGridPanelId = this.myId('user')
		this.userGroupsGridPanelId = this.myId('groups')

		Ext.apply(this, {
			layout : 'tdgi_border',
			defaults : {
				border : false
			},
			border : false,
			items : [{
				stateful : true,
				stateId : this.myId('groups'),
				region : 'east',
				title : '所属用户组',
				collapsible : true,
				ctCls : "j-toolbar-dark",
				width : 300,
				collapsedTitle : true,
				split : true,
				layout : 'fit',
				items : [{
					id : this.userGroupsGridPanelId,
					xtype : "panel.admin.UserGroupsGridPanel"
				}]
			}, {
				region : 'center',
				layout : 'fit',
				autoScroll : true,
				title : '用户帐号一览',
				ctCls : "j-toolbar-dark",
				items : [{
					id : this.userGridPanelId,
					xtype : "panel.admin.UserGridPanel"
				}]
			}]
		})
		
		this.subscribe("divo.rowSelect"+this.userGridPanelId,this.onUserChange,this)
		this.on('beforedestroy',function() {
		      this.unsubscribe()
		},this)

		divo.admin.user.MainPanel.superclass.initComponent.call(this)
	},
	//选择了某个用户
	onUserChange : function(subj, msg, data) {
		Ext.getCmp(this.userGroupsGridPanelId).showList(msg.id)
	}
})

divo.admin.user.Main = function() {
	/* ----------------------- private变量 ----------------------- */

	/* ----------------------- private方法 ----------------------- */
	// 创建布局
	function createLayout(parentPanel) {
		if (!divo.isAdmin()) {
			alert("只有系统管理员才能使用此功能。")
			return
		} //内部不再控制操作权限
		
		parentPanel.add(new divo.admin.user.MainPanel({
			id : 'admin-user'
		}))
		parentPanel.doLayout()
	}

	/* ----------------------- public方法 ----------------------- */
	return {

		// 初始化
		init : function(parentPanel, menuId) {
			createLayout(parentPanel)
		}

	} // return

}()
// EOP

;/**
 * 用户帐号信息管理
 */
panel.admin.UserGridPanel = Ext.extend(divo.panel.SmartGridDetailPanel, {
	initComponent : function() {
		if (!this.isLookup) {
			this.action = new Ext.ux.grid.RowActions({
				header : '操作',
				autoWidth : false,
				width : 100,
				actions : [{
					iconCls : 'icon-update',
					tooltip : '修改用户帐号信息',
					hideIndex : 'is_admin'
				}, {
					iconCls : 'icon-delete',
					tooltip : '删除用户帐号',
					hideIndex : 'is_admin'
				}, {
					iconIndex : 'activate_cls',
					qtipIndex : 'activate_tip',
					hideIndex : 'is_admin'
				}]
			})
			this.action.on('action', this.onAction, this)
		}

		Ext.apply(this, {
			url : "/users",
			fieldDefinitions : this.getListDefinitions(),
			gridConfig : {
				pageSize : 20,
				gridIdOfView : 'admin-user-grid', // 使网格视图Id始终保持不变
				filter : true,
				toolbar : this.isLookup ? false : this.createToolbarBtn(),
				plugins : this.isLookup
						? [new Ext.ux.grid.DragSelector()]
						: [this.action],
				footerSimple : this.isLookup,
				autoExpandColumn : 'name'
			},
			dialogTitle : "新建/修改 用户帐号",
			dialogWidth : 400,
			dialogHeight : 200,
			autoScroll : true
		})
		this.form = this.createForm()

		panel.admin.UserGridPanel.superclass.initComponent.apply(this,
				arguments)
	},
	onAction : function(grid, record, action, row, col) {
		if (action == 'icon-update')
			this.editItem()
		if (action == 'icon-delete')
			this.deleteItem()
		if (action == 'icon-active' || action == 'icon-not-active')
			this.setStatus(record.data.id)
	},
	// 重写
	createGridMeta : function() {
		return this.getGridMeta(this.fieldDefinitions,this.isLookup?null:[this.action])
	},
	getListDefinitions : function() {
		return [{
			name : 'id'
		}, {
			name : 'name',
			header : '用户名',
			searchable : true,
			type : 'string'
		}, {
			name : 'full_name',
			header : '姓名',
			searchable : true,
			type : 'string',
			id : 'name'
		},{
			name : 'email',
			header : '邮箱',
			searchable : true,
			type : 'string'
		}, {
			name : 'is_admin',
			type : 'bool',
			convert : function(v, rec) {
				return rec.id == 1
			}
		}, {
			name : 'activate_cls',
			type : 'string',
			convert : function(v, rec) {
				return (rec.active ? 'icon-not-active' : 'icon-active')
			}
		}, {
			name : 'activate_tip',
			type : 'string',
			convert : function(v, rec) {
				return (rec.active ? '休眠' : '激活')
			}
		}, {
			name : 'active',
			header : '状态',
			type : 'bool',
			hidden : this.isLookup,
			renderer : this.activeRender.createDelegate(this)
		}]
	},
	activeRender : function(value, p, record) {
		return (value ? '激活' : '休眠')
	},
	createForm : function() {
		return new divo.form.DivoForm({
			formType : "editOnly",
			showButtons : false,
			showTitle : false,
			alternateRows : false,
			labelClass : "label",
			fieldDefinitions : this.getFormDefinitions()
		})
	},
	getFormDefinitions : function() {
		return ([{
			field : "full_name",
			label : "姓名",
			required : true
		}, {
			field : "name",
			label : "用户名",
			required : true
		},{
			field : "email",
			label : "电子邮箱"
		}])
	},
	// 添加工具条按钮
	createToolbarBtn : function() {
		var tb = [];

		var addBtn = new Ext.Toolbar.Button({
			text : '新建帐号',
			tooltip : '新建用户帐号',
			icon : divo.iconAdd,
			cls : 'x-btn-text-icon',
			handler : this.addItem.createDelegate(this)
		})
		tb.push(addBtn)
		var resetBtn = new Ext.Toolbar.Button({
			text : '重置密码',
			tooltip : '登录密码重新设置为初始值',
			icon : divo.iconUrl + 'locked.gif',
			cls : 'x-btn-text-icon',
			handler : this.resetPassword.createDelegate(this)
		})
		tb.push(resetBtn)

		return tb
	},
	onLoadItem : function(id) {
		Ext.Ajax.request({
			scope : this,
			url : this.url + '/' + id,
			method : 'GET',
			success : function(response, options) {
				var resp = Ext.decode(response.responseText);
				this.fillForm(resp.data)
			},
			failure : function(response, options) {
				this.alert(response.responseText);
			}
		})
	},
	userNameValidate : function(v) {
		var t = /^[a-zA-Z0-9_\- ]+$/;
		return t.test(v)
	},
	userEmailValidate : function(v) {
		var t = /^\w+([-+.]\w+)*@\w+([-.]\\w+)*\.\w+([-.]\w+)*$/;
		return t.test(v)
	},
	//重写
	validateItem : function(item) {
		if (!this.userNameValidate(item.name)) {
			this.say("用户名只能是英文或数字。")
			return false
		}
		if (item.email && !this.userEmailValidate(item.email)){
		    this.say("请填写正确的邮箱格式！")
	 	    return false
		}
		return true
	},
	//重写
	onSaveItem : function(item) {
		this.form.clearErrorMessages()
		var adding = !item.id
		
		this.sayWait("保存")

		Ext.Ajax.request({
			scope : this,
			url : this.url + (adding ? '' : '/' + item.id),
			method : adding ? 'POST' : 'PUT',
			jsonData : item,
			success : function(response, options) {
				var resp = Ext.decode(response.responseText)
				this.saveItemCallback(adding, resp)
			},
			failure : function(response, options) {
				this.alert(response.responseText)
			}
		})
	},
	onDeleteItem : function(id) {
		Ext.Ajax.request({
			scope : this,
			url : this.url + '/' + id,
			method : 'DELETE',
			success : function(response, options) {
				var resp = Ext.decode(response.responseText)
				if (resp.success)
					this.deleteItemCallback()
				else
					this.say(resp.errors.reason)
			},
			failure : function(response, options) {
				this.alert(response.responseText)
			}
		})
	},
	setStatus : function(id) {
		var ok = true
		Ext.Ajax.request({
			scope : this,
			url : "users/" + id + "/state",
			async : false,
			method : 'PUT',
			success : function(response, options) {
				var resp = Ext.decode(response.responseText)
				if (resp.success) {
					this.say('状态改变成功')
				}
			},
			failure : function(response, options) {
				this.alert(response.responseText)
				ok = false
			}
		});
		if (ok) {
			this.loadList()
		}
	},
	resetPassword : function() {
		if (!this.cId) {
			this.say("请先选择用户。")
			return
		}
		if (this.cId == 1) {
			this.say("系统管理员的密码不允许重置。")
			return
		}
		Ext.MessageBox.confirm('确认', '要重置密码吗？', this.resetPasswordConfirm
				.createDelegate(this))
	},
	resetPasswordConfirm : function(btn) {
		if (btn !== 'yes')
			return

		var ok = true
		Ext.Ajax.request({
			scope : this,
			url : "users/" + this.cId + "/password/default",
			async : false,
			method : 'PUT',
			success : function(response, options) {
				var resp = Ext.decode(response.responseText)
				if (resp.success) {
					this.say('密码重置成功')
				}
			},
			failure : function(response, options) {
				this.alert(response.responseText)
				ok = false
			}
		});
		if (ok) {
			this.loadList()
		}

	}

})

Ext.reg('panel.admin.UserGridPanel', panel.admin.UserGridPanel);
// EOP

;/**
 * 用户所属用户组管理
 */
panel.admin.UserGroupsGridPanel = Ext.extend(divo.panel.SmartGridPanel, {
	initComponent : function() {
 		this.action = new Ext.ux.grid.RowActions({
            header:'',
            actions:[{
                iconCls:'icon-delete',
                tooltip:'删除与此用户组关联'
            }]
        })
		this.action.on('action',this.onAction,this)
	
		Ext.apply(this, {
			fieldDefinitions : this.getListDefinitions(),
			gridConfig : {
				gridIdOfView : 'admin-user-groups-grid',
				toolbar : this.createToolbarBtn(),
				plugins : [this.action],
				footer : false,
				displayLoadMask : false,
				autoExpandColumn : 'name'
			},
			autoScroll : true
		})
		
		this.subscribe("window.admin.UserGroupsChanged",this.onUserGroupsChanged,this)
		this.on('beforedestroy',function() {
		      this.unsubscribe()
		},this)
		
		panel.admin.UserGroupsGridPanel.superclass.initComponent.apply(this,arguments)
	},
	onAction : function(grid, record, action, row, col) {
		if (action=='icon-delete')
		    this.deleteUserGroup(record.data.id)
	},
	//重写
	createGridMeta : function() {
		return this.getGridMeta(this.fieldDefinitions,this.isLookup?null:[this.action])
	},
	getListDefinitions : function() {
		return [{
			name : 'id'
		},{
			name : 'name',
			header : '名称',
			type : 'string',
			id : 'name'
		}]
	},
	// 添加工具条按钮
	createToolbarBtn : function(){
		var tb = [];

		var addBtn = new Ext.Toolbar.Button( {
			text : '选择',
			tooltip : '指定所属用户组',
			icon : divo.iconAdd,
			cls : 'x-btn-text-icon',
			handler : this.selectUserGroups.createDelegate(this)
		})
		tb.push(addBtn)
		return tb
	},
	selectUserGroups : function() {
		if (!this.validate()) {
			return
		}
		this.userAndGroupWindowId = this.myId('win')
		
		var win = new window.admin.UserAndGroupWindow({
			id : this.userAndGroupWindowId,
			closeAction : "destroy",
			cancelAction : "destroy",
			userId : this.userId,
			userName : this.getUserFullName()
		})
		win.show()
	},
	onUserGroupsChanged : function(subj, msg, data) {
		if (msg.sender==this.userAndGroupWindowId) {
			this.showList()
		}
	},
	deleteUserGroup : function(groupId) {
		if (!this.validate()) {
			return
		}
		var ok = true
		Ext.Ajax.request({
			scope : this,
			url : "/users/"+this.userId+"/groups/"+groupId,
			async : false,
			method : 'DELETE',
			success : function(response, options) {
				var resp = Ext.decode(response.responseText)
				if (!resp.success) {
					ok = false
				    this.say(resp.errors.reason)
				}     
			},
			failure : function(response, options) {
				this.alert(response.responseText)
				ok = false
			}
		});
		if (ok) {
			this.showList()
		}
	},
	validate : function() {
		if (!this.userId) {
			this.say("请选择用户")
			return false
		}
		if (this.userId == 1) {
			this.say("系统管理用户不允许变动所属用户组")
			return false
		}
		return true
	},
	//public
	showList : function(userId) {
	   if (userId)
	   	   this.userId = userId
	   
	   if (!this.userId) return
	   
	   this.setUrl("/users/"+this.userId+"/groups")
  	   this.loadList()
	},
	getUserFullName : function() {
		var fullName = ''
		Ext.Ajax.request({
			scope : this,
			url : "/users/"+this.userId,
			async : false,
			method : 'GET',
			success : function(response, options) {
				var resp = Ext.decode(response.responseText)
				if (!resp.success) {
					this.say(resp.errors.reason)
					return
				}
				fullName = resp.data.full_name
			},
			failure : function(response, options) {
				this.alert(response.responseText)
			}
		})
		return fullName
	}
})

Ext.reg('panel.admin.UserGroupsGridPanel', panel.admin.UserGroupsGridPanel);
// EOP

;/**
 * 选择所属用户组表单
 */
form.admin.UserAndGroupForm = Ext.extend(Ext.form.FormPanel, {
	userId : null,
	initComponent : function() {
		
		Ext.apply(this, {
			baseCls : "x-plain",
			labelWidth : 75,
			labelAlign : "right",
			autoScroll : true,
			bodyStyle : "padding:0",
			items : [{
				xtype : "itemselector",
				name : 'user_groups',
				hideLabel : true,
				fromStore:this.getFromDataStore(),
				toStore:this.getToDataStore(),
				msWidth:250,
				msHeight:200,
				valueField : "id",
				displayField : "name",
				toLegend:"已选",
				fromLegend:"候选",
				drawUpIcon:false,
				drawDownIcon:false,
				drawTopIcon:false,
				drawBotIcon:false
			}]
		});

		form.admin.UserAndGroupForm.superclass.initComponent.call(this);
	},
	// 保存选择的用户组
	save : function(callbackOnSuccess) {	
		var itemStr = this.getForm().getObjectValues()
		if (itemStr.user_groups.length>0)
		    var items = itemStr.user_groups
		else    
		    var items = null 

		//删除现有全部所属用户组
		if (!this.deleteAll()) return
		
		//存入新的用户组
		var ok = true
		if (items) {
		    ok = this.saveAll(items)
		}
		if (ok) {
			this.say("选择的用户组已经保存")
			callbackOnSuccess.call()
		}
	},
	getFromDataStore : function() {
		return new Ext.data.Store({					 
			autoLoad: true,
			proxy : new Ext.data.HttpProxy( {
				method : 'GET',
				url : "/users/"+this.userId+"/groups/avaiable"
			}),
			reader: this.getReader(),
			sortInfo:{field:'name', direction:'ASC'},
        	listeners: {
        		loadexception: function(o,options,response,e) {
			 		divo.showError(response.responseText,'数据加载失败')
        		},
        		scope: this
        	}
		})		
	},
	getToDataStore : function() {
		return new Ext.data.Store({					 
			autoLoad: true,
			proxy : new Ext.data.HttpProxy( {
				method : 'GET',
				url : "/users/"+this.userId+"/groups"
			}),
			reader: this.getReader(),
			sortInfo:{field:'name', direction:'ASC'}
		})		
	},
	getReader : function() {
		return new Ext.data.JsonReader({
			idProperty:'id',
			root:'rows',
			fields: [
				{name: 'id', type: 'int'},
				{name: 'name', type: 'string'}
			]
		})		
	},
	deleteAll : function() {
		var ok = true
		Ext.Ajax.request({
			scope : this,
			url : "users/"+this.userId+"/groups",
			async : false,
			method : 'DELETE',
			success : function(response, options) {
				var resp = Ext.decode(response.responseText)
				if (!resp.success) {
					ok = false
				    this.say(resp.errors.reason)
				}     
			},
			failure : function(response, options) {
				this.alert(response.responseText)
				ok = false
			}
		});
		return ok
	},
	saveAll : function(items) {
		var ok = true
		Ext.Ajax.request({
			scope : this,
			url : "users/"+this.userId+"/groups",
			async : false,
			method : 'POST',
			jsonData : {idList:items}, //用逗号分隔的id值列表
			failure : function(response, options) {
				this.alert(response.responseText)
				ok = false
			}
		});
		return ok
	}
});

Ext.reg("form.admin.UserAndGroupForm", form.admin.UserAndGroupForm);
// EOP

;/**
 * 用户所属用户组维护窗口
 * 
 * --------------------------------------------------------------
 * 消息：
 * 用户所属用户组有了变动
 * 
 * 消息名：     			
 * window.admin.UserGroupsChanged 
 * 
 * 消息内容：
 * {int} sender 当前组件Id
 * --------------------------------------------------------------
 * 
 */
window.admin.UserAndGroupWindow = Ext.extend(Ext.Window, {
	cancelAction : "hide",  //还可以取值：destroy
	closeAction : "hide",
	userId : null,
	userName : null,
	initComponent : function() {
		Ext.apply(this,{
			title : '选择所属用户组 - '+this.userName,
			width : 550,	
			height : 300,
			modal : true,
			closable : true,
			maximizable : false,
			minimizable : false,
			layout : "fit",
			buttons : [{
				text : "确定",
				handler : this.onSave,
				scope : this
			}, {
				text : "取消",
				handler : this.onCancel,
				scope : this
			}],
			items : {
				xtype : "form.admin.UserAndGroupForm",
				userId : this.userId
			}
		});
		
		window.admin.UserAndGroupWindow.superclass.initComponent.call(this);
	},
	onSave : function() {
		this.items.itemAt(0).save(this.onSaveSucccess.createDelegate(this))
	},
	onSaveSucccess : function() {
		this.close()
		this.publish("window.admin.UserGroupsChanged",{sender:this.id})
	}
});
// EOP

;